const itemsPerPage = 5; // 每页显示的医院数量
let currentPage = 1;
let hospitals = [];

// 从后端 API 获取医院数据
fetch('/webapi/patient/rank')
    .then(response => response.json())
    .then(data => {
        hospitals = data.sort((a, b) => b.score - a.score); // 按评分降序排序
        const totalPages = Math.ceil(hospitals.length / itemsPerPage);
        document.getElementById('totalPages').innerText = totalPages;
        renderTable();
        updateButtons();
    })
    .catch(error => console.error('获取医院数据失败:', error));

function renderTable() {
    const tableBody = document.getElementById('hospitalTable').getElementsByTagName('tbody')[0];
    tableBody.innerHTML = ''; // 清空表格内容
    const start = (currentPage - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    const paginatedHospitals = hospitals.slice(start, end);

    paginatedHospitals.forEach((hospital, index) => {
        const row = tableBody.insertRow();
        row.innerHTML = `
                <td>${start + index + 1}</td>
                <td>${hospital.name}</td>
                <td>${hospital.score.toFixed(1)}</td>
                <td>${hospital.address}</td>
            `;
    });

    document.getElementById('currentPage').innerText = currentPage;
}

function updateButtons() {
    document.getElementById('prevPage').disabled = currentPage === 1;
    document.getElementById('nextPage').disabled = currentPage === Math.ceil(hospitals.length / itemsPerPage);
}

document.getElementById('prevPage').addEventListener('click', () => {
    if (currentPage > 1) {
        currentPage--;
        renderTable();
        updateButtons();
    }
});

document.getElementById('nextPage').addEventListener('click', () => {
    if (currentPage < Math.ceil(hospitals.length / itemsPerPage)) {
        currentPage++;
        renderTable();
        updateButtons();
    }
});